//
//  Sun.m
//  test
//
//  Created by sunshine on 16/10/8.
//  Copyright © 2016年 sun. All rights reserved.
//

#import "Sun.h"
@interface Sun()
@property(nonatomic,strong)NSMutableDictionary *data;//only shared
@property(nonatomic,strong)UIView *black;
@property(nonatomic,strong)UIView *backGround;
@property(nonatomic,strong)UITapGestureRecognizer *tap;
@property(nonatomic,strong)UIView *act;
@property(nonatomic,strong)UIView *msg;
@property(nonatomic,assign)BOOL isMiss;
@property(nonatomic,strong)NSTimer *timer;
@end
@implementation Sun
static Sun *sun = nil;
+ (instancetype)shareSun{
    @synchronized(self)
    {
        if(sun==nil){
            sun=[[Sun alloc]init];
            sun.data = [NSMutableDictionary dictionary];
        }
        return sun;
    }
}
- (void)dealloc{
    [self.timer invalidate];
    self.black = nil;
    self.backGround = nil;
    self.act = nil;
    self.msg = nil;
    self.timer = nil;
}
- (void)show:(UIView *)view to:(id)target shouldReturn:(BOOL)shouldReturn{
    [self hideAll];
    if (!self.black) {
        self.black = [[UIView alloc]init];
        self.black.backgroundColor = [UIColor blackColor];
        self.black.alpha = 0.7;
    }
    if (!self.backGround) {
        self.backGround = [[UIView alloc]init];
    }
    if (shouldReturn) {
        if (!self.tap) {
            self.tap = [[UITapGestureRecognizer alloc]init];
            [self.backGround addGestureRecognizer:self.tap];
        }
        [self.tap addTarget:self action:@selector(hideShow)];
    }else {
        if (self.tap) {
            [self.tap removeTarget:self action:@selector(hideShow)];
        }
    }
    [self.black lt_removeAllCons];
    [self.backGround lt_removeAllCons];
    for (int i=0; i<self.backGround.subviews.count; i++) {
        [self.backGround.subviews[i] removeFromSuperview];
        i--;
    }
    if ([target isKindOfClass:[UIViewController class]]) {
        UIViewController *controller = target;
        [controller.view addSubview:self.black];
        [controller.view addSubview:self.backGround];
        [controller.view bringSubviewToFront:self.black];
        [controller.view bringSubviewToFront:self.backGround];
    }
    if ([target isKindOfClass:[UIView class]]) {
        UIView *parentView = target;
        [parentView addSubview:self.black];
        [parentView addSubview:self.backGround];
        [parentView bringSubviewToFront:self.black];
        [parentView bringSubviewToFront:self.backGround];
    }
    if ([target isKindOfClass:[UIWindow class]]) {
        UIWindow *window = target;
        [window addSubview:self.black];
        [window addSubview:self.backGround];
        [window bringSubviewToFront:self.black];
        [window bringSubviewToFront:self.backGround];
    }
    [self.black lt_All:SunEdgesMake(0, 0, 0, 0) save:YES];
    [self.backGround lt_All:SunEdgesMake(0, 0, 0, 0) save:YES];
    [self.backGround addSubview:view];
    [view lt_XYcenterTo:nil save:YES];
}
- (void)alertAlign:(NSTextAlignment)align title:(NSString *)title content:(NSString *)content  left:(NSString *)left right:(NSString *)right cancel:(CancelBlock)cancel sure:(SureBlock)sure To:(UIViewController *)viewController{
    self.cancelBlock = cancel;
    self.sureBlock = sure;
    UIColor *mainColor = [HXColor colorWithHexString:@"FB8866"];
    UIView *alert = [[UIView alloc]init];
    alert.backgroundColor = [UIColor whiteColor];
    alert.layer.cornerRadius = 8;
    alert.clipsToBounds = YES;
    UILabel *titleLabel = [[UILabel alloc]init];
    [alert addSubview:titleLabel];
    [titleLabel lt_XcenterTo:nil save:YES];
    titleLabel.textColor = [HXColor colorWithHexString:@"333333"];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.text = title;
    UILabel *contentLabel = [[UILabel alloc]init];
    [alert addSubview:contentLabel];
    [contentLabel lt_XcenterTo:nil save:YES];
    [contentLabel lt_setTop:Y(20) to:titleLabel save:YES];
    contentLabel.numberOfLines = 0;
    contentLabel.preferredMaxLayoutWidth = X(265);
    contentLabel.textColor = [HXColor colorWithHexString:@"666666"];
    contentLabel.font = [UIFont systemFontOfSize:14];
    contentLabel.textAlignment = align;
    contentLabel.text = content;
    UIButton *leftBtn = [[UIButton alloc]init];
    [alert addSubview:leftBtn];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn setTitle:left forState:UIControlStateNormal];
    [leftBtn setBackgroundColor:mainColor forState:UIControlStateNormal];
    [leftBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [leftBtn setTitleColor:mainColor forState:UIControlStateHighlighted];
    leftBtn.layer.cornerRadius = Y(21);
    leftBtn.clipsToBounds = YES;
    leftBtn.layer.borderWidth = 1;
    leftBtn.layer.borderColor = mainColor.CGColor;
    [leftBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    if (!sure) {
        [alert addSubview:leftBtn];
        [leftBtn lt_setSize:CGSizeMake(X(120), X(40)) save:YES];
        [leftBtn lt_setTop:Y(30) to:contentLabel save:YES];
        [leftBtn lt_XcenterTo:nil save:YES];
    }else {
        UIButton *rightBtn = [[UIButton alloc]init];
        [alert addSubview:rightBtn];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [rightBtn setTitle:right forState:UIControlStateNormal];
        [rightBtn setBackgroundColor:[UIColor colorWithHexString:@"CCCCCC"] forState:UIControlStateHighlighted];
        [rightBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [rightBtn setTitleColor:[UIColor colorWithHexString:@"CCCCCC"] forState:UIControlStateNormal];
        rightBtn.layer.cornerRadius = Y(21);
        rightBtn.clipsToBounds = YES;
        rightBtn.layer.borderWidth = 1;
        rightBtn.layer.borderColor = [UIColor colorWithHexString:@"CCCCCC"].CGColor;
        [rightBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:leftBtn];
        [leftBtn lt_setSize:CGSizeMake(X(120), X(40)) save:YES];
        [leftBtn lt_setTop:Y(30) to:contentLabel save:YES];
        [leftBtn lt_setLeft:X(34) to:nil save:YES];
        [alert addSubview:rightBtn];
        [rightBtn lt_setSize:CGSizeMake(X(120), X(40)) save:YES];
        [rightBtn lt_YcenterTo:leftBtn save:YES];
        [rightBtn lt_setRight:X(34) to:nil save:YES];
    }
    [self show:alert to:viewController shouldReturn:NO];
    [alert lt_setWidth:X(333) save:YES];
    [alert lt_layoutView:alert side:SunTop to:titleLabel toSide:SunTop withSize:1 offset:-Y(15) save:YES];
    [alert lt_layoutView:alert side:SunBottom to:leftBtn toSide:SunBottom withSize:1 offset:Y(15) save:YES];
}
- (void)cancelAction{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}
- (void)sureAction{
    if (self.sureBlock) {
        self.sureBlock();
    }
}
- (void)showActivity:(UIViewController *)controller{
    if (!self.act) {
        self.act = [[UIView alloc]init];
        UIView *actBack = [[UIView alloc]init];
        [self.act addSubview:actBack];
        actBack.backgroundColor = [UIColor blackColor];
        actBack.alpha = 0.8;
        actBack.layer.cornerRadius = 5;
        actBack.layer.borderWidth = 1;
        actBack.layer.borderColor = [UIColor grayColor].CGColor;
        [actBack lt_XYcenterTo:nil save:YES];
        UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [self.act addSubview:actView];
        [actView startAnimating];
        UILabel *label = [[UILabel alloc]init];
        [self.act addSubview:label];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        label.text = @"正在努力加载中";
        [actView lt_XcenterTo:nil save:YES];
        [label lt_XcenterTo:nil save:YES];
        [label lt_setTop:15 to:actView save:YES];
        [actBack lt_layoutView:actBack side:SunTop to:actView toSide:SunTop withSize:1 offset:-15 save:YES];
        [actBack lt_layoutView:actBack side:SunBottom to:label toSide:SunBottom withSize:1 offset:15 save:YES];
        [actBack lt_layoutView:actBack side:SunWidth to:label toSide:SunWidth withSize:1 offset:30 save:YES];
    }
    [controller.view addSubview:self.act];
    [controller.view bringSubviewToFront:self.act];
    [self.act lt_All:SunEdgesMake(0, 0, 0, 0) save:YES];
}
- (void)showMsg:(NSString *)msg{
    UILabel *msgLabel;
    if (!self.msg) {
        self.msg = [[UIView alloc]init];
        UIView *backView = [[UIView alloc]init];
        [self.msg addSubview:backView];
        backView.backgroundColor = [UIColor blackColor];
        backView.alpha = 0.7;
        backView.layer.cornerRadius = 5;
        backView.layer.borderWidth = 1;
        backView.layer.borderColor = [UIColor grayColor].CGColor;
        [backView lt_XYcenterTo:nil save:YES];
        msgLabel = [[UILabel alloc]init];
        msgLabel.tag = 1;
        msgLabel.textColor = [UIColor whiteColor];
        msgLabel.font = [UIFont systemFontOfSize:16];
        msgLabel.numberOfLines = 0;
        msgLabel.textAlignment = NSTextAlignmentCenter;
        [self.msg addSubview:msgLabel];
        NSArray *cons = [NSLayoutConstraint constraintsWithVisualFormat:@"[view(<=200)]" options:0 metrics:nil views:@{@"view":msgLabel}];
        [self.msg addConstraints:cons];
        [msgLabel lt_XYcenterTo:nil save:YES];
        msgLabel.text = msg;
        [backView lt_layoutView:backView side:SunWidth to:msgLabel toSide:SunWidth withSize:1 offset:36 save:YES];
        [backView lt_layoutView:backView side:SunHeight to:msgLabel toSide:SunHeight withSize:1 offset:24 save:YES];
        
    }else{
        msgLabel = [self.msg viewWithTag:1];
        msgLabel.text = msg;
    }
    if (!self.msg.superview) {
        [[UIApplication sharedApplication].keyWindow addSubview:self.msg];
        [self.msg lt_removeAllCons];
        [self.msg lt_XcenterTo:nil save:YES];
        [self.msg lt_layoutView:self.msg side:SunBottom to:nil toSide:SunBottom withSize:0.7 offset:0 save:YES];
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.msg];
        self.timer=[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideMsg) userInfo:nil repeats:NO];
    }
}
- (void)hideMsg{
    [self.msg removeFromSuperview];
}
- (void)hideActivity{
    if (self.act) {
        [self.act removeFromSuperview];
    }
}
- (void)hideShow{
    if (self.black) {
        [self.black removeFromSuperview];
    }
    if (self.backGround) {
        for (int i=0; i<self.backGround.subviews.count; i++) {
            [self.backGround.subviews[i] removeFromSuperview];
            i--;
        }
        [self.backGround removeFromSuperview];
    }
}
- (void)hideAll{
    if (self.black) {
        [self.black removeFromSuperview];
    }
    if (self.backGround) {
        [self.backGround removeFromSuperview];
    }
    if (self.act) {
        [self.act removeFromSuperview];
    }
}
+ (id)getUser:(NSString *)key{
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
+ (void)setUser:(id)value forKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults]setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+ (NSString *)timestamp:(NSTimeInterval)timestamp ToTime:(NSString *)type{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:type];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    return [formatter stringFromDate:date];
}
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+ (UIImage *)imageWithColorFrom:(UIColor *)startColor To:(UIColor *)endColor Frame:(CGRect)frame Direction:(SunDirection)direction{
    CIFilter *ciFilter = [CIFilter filterWithName:@"CILinearGradient"];
    CIVector *vector0;
    CIVector *vector1;
    switch (direction) {
        case SunDirectionBottom:
            vector0 = [CIVector vectorWithX:frame.size.width Y:frame.size.height];
            vector1 = [CIVector vectorWithX:frame.size.width Y:0];
            break;
        case SunDirectionRight:
            vector0 = [CIVector vectorWithX:0 Y:frame.size.height];
            vector1 = [CIVector vectorWithX:frame.size.width Y:frame.size.height];
            break;
        case SunDirectionDiagonal0:
            vector0 = [CIVector vectorWithX:0 Y:frame.size.height];
            vector1 = [CIVector vectorWithX:frame.size.width Y:0];
            break;
        case SunDirectionDiagonal1:
            vector0 = [CIVector vectorWithX:frame.size.width Y:frame.size.height];
            vector1 = [CIVector vectorWithX:0 Y:0];
            break;
        default:
            break;
    }
    [ciFilter setValue:vector0 forKey:@"inputPoint0"];
    [ciFilter setValue:vector1 forKey:@"inputPoint1"];
    [ciFilter setValue:[CIColor colorWithCGColor:startColor.CGColor] forKey:@"inputColor0"];
    [ciFilter setValue:[CIColor colorWithCGColor:endColor.CGColor] forKey:@"inputColor1"];
    CIImage *ciImage = ciFilter.outputImage;
    CIContext *con = [CIContext contextWithOptions:nil];
    CGImageRef resultCGImage = [con createCGImage:ciImage fromRect:frame];
    UIImage *resultUIImage = [UIImage imageWithCGImage:resultCGImage];
    CGImageRelease(resultCGImage);
    [resultUIImage drawInRect:frame];
    return resultUIImage;
}
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:lineColor.CGColor];
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [lineView.layer addSublayer:shapeLayer];
}
+ (NSString *)formatStringToMoney:(NSString *)money{
    if (!money) {
        return @"0";
    }
    NSMutableString *string = [NSMutableString stringWithString:money];
    NSRange range = [money rangeOfString:@"."];
    NSInteger index = 0;
    if (range.length > 0) {
        index = range.location;
    }else {
        index = money.length;
    }
    while ((index - 3) > 0) {
        index -= 3;
        [string insertString:@"," atIndex:index];
    }
    return string;
}
+ (NSString *)formatStringToPhone:(NSString *)string{
    if (string.length > 3 && [string characterAtIndex:3] != ' '){
        string = [[[string substringToIndex:3]stringByAppendingString:@" "]stringByAppendingString:[string substringFromIndex:3]];
    }
    if (string.length > 8 && [string characterAtIndex:8] != ' '){
        string = [[[string substringToIndex:8]stringByAppendingString:@" "]stringByAppendingString:[string substringFromIndex:8]];
    }
    return  string;
}
+ (NSString *)formatStringToBank:(NSString *)bankNum{
    if (bankNum.length) {
        NSString *text = bankNum;
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        return newString;
    }
    return bankNum;
}
+ (NSString *)hidePhone:(NSString *)string{
    string = [[[string substringToIndex:3]stringByAppendingString:@"****"]stringByAppendingString:[string substringFromIndex:7]];
    return  string;
}
+ (BOOL)checkPhone:(NSString *)phone{
    if (phone.length == 11 && [phone characterAtIndex:0] == '1') {
        return YES;
    } else {
        return NO;
    }
}
+ (id)copyWithView:(UIView *)view{
    NSData *oldViewData =  [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:oldViewData];
}
+ (NSString *)htmlFormat:(NSString *)str{
    while ([str rangeOfString:@">"].length > 0) {
        NSInteger a = [str rangeOfString:@">" options:NSBackwardsSearch].location;
        NSInteger b = [str rangeOfString:@"<" options:NSBackwardsSearch range:NSMakeRange(0, a)].location;
        str = [str stringByReplacingCharactersInRange:NSMakeRange(b, a - b + 1) withString:@""];
    }
    while ([str rangeOfString:@"\n\n"].length > 0) {
        str = [str stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
    }
    str = [str stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    return str;
}
+ (void)labelSetLineHeight:(float)height To:(UILabel *)label{
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:height];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
    [label setAttributedText:attributedString];
    [label sizeToFit];
}
+ (NSDictionary *)dictionaryFromUrlString:(NSString *)urlStr{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    while ([urlStr containsString:@" "]) {
        urlStr = [urlStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.length == 0) {
        return nil;
    }
    NSString * string = [urlStr substringFromIndex:range.location + 1];
    NSArray *arr = [string componentsSeparatedByString:@"&"];
    for (int i=0; i<arr.count; i++) {
        NSArray *arr2 = [arr[i] componentsSeparatedByString:@"="];
        [result setObject:arr2[1] forKey:arr2[0]];
    }
    return result;
}

+ (NSString *)stringFromDictionary:(NSDictionary *)dic{
    NSArray *keyArr = [dic allKeys];
    NSMutableString *result = [NSMutableString string];
    for (NSString *key in keyArr) {
        if (result.length > 0) {
            [result appendString:@"&"];
        }
        [result appendString:key];
        [result appendString:@"="];
        [result appendString:[dic objectForKey:key]];
    }
    return result;
}
@end
